package com.cjy.beans;


import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cheng jiye
 * @date 2020/3/27
 */
public class BeanUtils {
    /**
     * 拷贝对象
     *
     * @param dest 目标对象
     * @param orig 源对象
     */
    public static void copyProperties(Object dest, Object orig) {
        try {
            org.apache.commons.beanutils.BeanUtils.copyProperties(dest, orig);
        } catch (Exception e) {
            throw new RuntimeException("Copy properties error!", e);
        }
    }

    /**
     * 创建实例
     *
     * @param clazz
     * @return
     */
    public static <T> T newInstance(Class<T> clazz) {
        if (clazz == null) {
            return null;
        }

        try {
            T obj = clazz.newInstance();
            return obj;
        } catch (Exception e) {
            throw new RuntimeException("New instance error!");
        }
    }

    /**
     * 把orig 拷贝到clazz中
     * orig有设则复制其属性到业务对象
     *
     * @param clazz 业务对象Class
     * @param orig  源对象
     * @return
     */
    public static <T> T copyEntity(Class<T> clazz, Object orig) {
        T entity = BeanUtils.newInstance(clazz);
        //属性复制
        if (orig != null) {
            BeanUtils.copyProperties(entity, orig);
        }
        return entity;
    }

    /**
     * 将类的List转换为另一个类的List
     *
     * @param origList  源对象List
     * @param destClass 目标对象Class
     */
    public static <T> List<T> convertBeanList(List<?> origList, Class<T> destClass) {
        Assert.notNull(destClass, "Class can't be empty!");

        if (origList == null) {
            return null;
        }

        List<T> destList = new ArrayList<>();

        if (origList.size() != 0) {
            for (Object orig : origList) {
                T dest = convertBean(orig, destClass);
                destList.add(dest);
            }
        }

        return destList;
    }

    /**
     * 将类转换为另一个类
     *
     * @param orig      源对象
     * @param destClass 目标对象Class
     * @return
     */
    public static <T> T convertBean(Object orig, Class<T> destClass) {
        Assert.notNull(destClass, "Class can't be empty!");

        if (orig == null) {
            return null;
        }

        try {
            T dest = newInstance(destClass);
            copyProperties(dest, orig);
            return dest;
        } catch (Exception e) {
            throw new RuntimeException("Convert bean error！", e);
        }
    }


}
